package core

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/layheart/gameServer/global"
	"gitee.com/layheart/gameServer/model/common/request"
	"gitee.com/layheart/gameServer/router"
	"go.uber.org/zap"
	"net"
	"strconv"
)

// Handle 处理
func Handle(conn net.Conn) {

	clientAddr := conn.RemoteAddr()
	global.Logger.Info("Client connected\n", zap.String("client connected", fmt.Sprintf("Client %s connected", clientAddr)))

	for {
		// 解析数据
		err := handleData(conn)
		if err != nil {
			if err.Error() == "EOF" {
				global.Logger.Error("客户端断开连接:", zap.Error(err))
				return
			}
			global.Logger.Error("handle-err:", zap.Error(err))
			continue
		}
	}
}

// 读取数据
func readData(conn net.Conn) (string, error) {

	// 读取长度
	lengthData := make([]byte, global.CONFIG.Server.HeaderContentSize)
	_, err := conn.Read(lengthData)
	if err != nil {
		return "", err
	}

	// 解析长度字段
	//dataLength := binary.BigEndian.Uint32(lengthData)
	dataLength, _ := strconv.Atoi(string(lengthData)) // 直接拼接的是长度

	// 读取实际数据
	data := make([]byte, dataLength)
	_, err = conn.Read(data)
	if err != nil {
		global.Logger.Error("Error reading data:", zap.Error(err))
		return "", err
	}

	return string(data), nil
}

// 处理数据
func handleData(conn net.Conn) error {

	// 接收数据
	params, err := readData(conn)
	if err != nil {
		return err
	}

	var requestParams request.RequestParams
	err = json.Unmarshal([]byte(params), &requestParams)
	if err != nil {
		global.Logger.Error("json.Unmarshal-err:", zap.Error(err))
		return err
	}

	// 断言路径对应的文件是否存在
	handle, ok := router.RouterGroupApp.RouterGroupList[requestParams.Method]
	if !ok {
		errMsg := "请求方法不存在,methodStr:" + requestParams.Method
		return errors.New(errMsg)
	}
	// 业务处理
	ctx := context.Background()
	ctx = context.WithValue(ctx, "params", requestParams.Data)
	ctx = context.WithValue(ctx, "conn", conn)
	err = handle(ctx)
	if err != nil {
		return err
	}
	return nil
}
